﻿using IRepository;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
using XingWeiDaWMSProject.Controllers;
using IService;
using Entity;
using Repository;

namespace XingWeDaWMSProject.Controllers
{
    public class CustomerManagementController : BaseController
    {

        private readonly ICustomerService _customerService;

        private readonly IWebHostEnvironment _webHostEnv; // 用于获取wwwroot路径

        private readonly IPublicAttachmentsService _attachmentService;



        public CustomerManagementController(ICustomerService customerService, IWebHostEnvironment webHostEnv, IPublicAttachmentsService attachmentService)
        {
            _customerService = customerService; // 确保注入不为 null
            _webHostEnv = webHostEnv;
            _attachmentService = attachmentService;
        }


        public IActionResult Index()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        public IActionResult Add()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }




        /// <summary>
        /// 客户分页信息显示
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetCustomerPage2(
            string customer_code = null,
            string customer_name = null,
            int? status = null,
            int? job_type = null,
            int? person_in_charge = null,
            string contact_person = null,
            int currentPage = 1,
            int pageSize = 1)    // 默认每页1条
        {
            try
            {
                // 调用服务层获取分页数据
                var paginationResult = await _customerService.GetAllCustomerAsync(
                  customer_code, customer_name, status, job_type, person_in_charge, contact_person,currentPage, pageSize);

                // 返回规范格式（前端可直接解析）
                return Json(new
                {
                    success = true,
                    data = paginationResult.items,  // 当前页数据
                    total = paginationResult.total, // 总条数
                    message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    data = new List<SupplierListDTO>(),
                    total = 0,
                    message = $"查询失败：{ex.Message}"
                });
            }

        }


        //新增客户方法

        [HttpPost]
        public async Task<IActionResult> AddCustomer([FromBody] WMSBasicCustomer customer)
        {
            try
            {
                int newCustomerId = await _customerService.AddCustomerAsync(customer);
                return Ok(new { success = true, customerId = newCustomerId, message = "新增成功" });
            }
            catch (ArgumentException ex)
            {
                // 输出参数错误详情
                Console.WriteLine($"参数错误：{ex.Message}\n堆栈跟踪：{ex.StackTrace}");
                return BadRequest(new { success = false, message = ex.Message });
            }
            catch (Exception ex)
            {
                // 输出系统异常详情（关键：捕获所有异常并打印堆栈）
                Console.WriteLine($"系统异常：{ex.Message}\n堆栈跟踪：{ex.StackTrace}");
                // 开发环境可返回详细错误信息（生产环境需隐藏）
                return StatusCode(500, new
                {
                    success = false,
                    message = "系统异常，请联系管理员",
                    detail = ex.Message // 仅开发环境添加，方便调试
                });
            }
        }




        /// <summary>
        /// 处理附件上传的接口
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            try
            {
                // 1. 校验文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Json(new { success = false, message = "请选择要上传的文件" });
                }

                // 2. 生成唯一附件编号（用于关联供应商）
                string annexCode = Guid.NewGuid().ToString("N");

                // 3. 定义文件保存路径（wwwroot/Uploads/Supplier）
                string saveDir = Path.Combine(_webHostEnv.WebRootPath, "Uploads", "Customer");
                if (!Directory.Exists(saveDir))
                {
                    Directory.CreateDirectory(saveDir); // 目录不存在则创建
                }

                // 4. 生成带唯一标识的文件名（避免重名）
                string fileName = $"{annexCode}_{Path.GetFileName(file.FileName)}";
                string fullPath = Path.Combine(saveDir, fileName);

                // 5. 保存文件到磁盘
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 6. 构造“附件记录”并插入数据库
                var attachment = new SysOrgPublicAttachments
                {
                    annex_code = annexCode,               // 与供应商关联的附件编号
                    type_of_business = "Customer",        // 业务类型（标识是“供应商”的附件）
                    order_no = "",                        // 可后续关联供应商编码（当前先空）
                    upload_image = fullPath.Replace(_webHostEnv.WebRootPath, "").Replace("\\", "/"), // 存储相对路径
                    uploader = 1,                         // 上传人ID（临时写死，需后续从登录态获取）
                    create_by = "admin",                  // 创建人（临时写死，需后续从登录态获取）
                    create_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), // 创建时间
                    attachment = annexCode // 关键：给attachment赋值（用附件编号或其他有意义的值）
                };
                await _attachmentService.AddAsync(attachment); // 调用服务层插入数据库

                // 7. 返回成功结果（包含附件编号，供后续关联供应商）
                return Json(new
                {
                    success = true,
                    data = new { annex_code = annexCode },
                    message = "文件上传成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    message = $"上传失败：{ex.Message}"
                });
            }
        }


        public IActionResult Detail()
        {
            return View();
        }


        // 提供给前端的客户详情查询接口
        [HttpGet]
        public async Task<ActionResult> GetCustomerDetail(string customerCode)
        {
            try
            {
                var customer = await _customerService.GetCustomerByCodeAsync(customerCode);
                if (customer == null)
                {
                    return Json(new { success = false, message = "客户不存在" });
                }
                return Json(new { success = true, data = customer });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }


        public IActionResult Edit()
        {
            return View();
        }


        //客户编辑查询信息
        [HttpGet]
        public async Task<IActionResult> GetCustomerEdit(string customerCode)
        {
            try
            {
                // 直接调用服务层（服务层已处理空值）
                var customer = await _customerService.GetCustomerByCode(customerCode);

                if (customer != null)
                {
                    return Ok(new
                    {
                        success = true,
                        data = customer,
                        message = "查询成功"
                    });
                }
                else
                {
                    // 涵盖两种情况：客户编号为空 或 未找到客户
                    return Ok(new
                    {
                        success = false,
                        message = string.IsNullOrWhiteSpace(customerCode) ? "客户编号不能为空" : "未找到该客户信息"
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询异常：{ex.Message}");
                return Ok(new
                {
                    success = false,
                    message = "查询失败，请稍后重试"
                });
            }
        }


        //编辑客户信息修改方法
        [HttpPut]
        public async Task<IActionResult> UpdateCustomer( [FromBody] WMSBasicCustomer customer)
        {
           
            try
            {
                // 3. 调用服务层更新方法（服务层直接转发仓储层结果）
                int affectedRows = await _customerService.UpdateCustomer(customer);

                // 4. 根据受影响行数返回结果
                return affectedRows > 0
                    ? Ok(new { Success = true, Message = "更新成功" })
                    : NotFound(new { Success = false, Message = "客户不存在或数据未变更" });
            }
            catch (Exception ex)
            {
                // 5. 捕获异常（如数据库错误）
                return StatusCode(500, new { Success = false, Message = $"更新失败：{ex.Message}" });
            }
        }



        [HttpPut]
        public async Task<IActionResult> DeleteCustomer([FromBody] DeleteRequest request)
        {
            try
            {
                int affectedRows = await _customerService.UpdateIsDelete(request.CustomerCode, request.IsDelete);
                return Ok(new { Success = true, Message = affectedRows > 0 ? "删除成功" : "未找到客户" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }


    }
}
